package picapi

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"iot-base/common/cache"
	"iot-base/common/dbconn"
	"iot-base/common/logger"
	"iot-base/common/pic"
	"iot-base/common/webapi"
	"os"
	//"path/filepath"
	"time"
)

func makeCondition(begin, end string) (string, string) {
	now := time.Now()
	var begint time.Time
	if begin == "" {
		d, _ := time.ParseDuration("-24h")
		begint = now.Add(d)
		begin = begint.Format("2006-01-02 15:04:05")
	} else {
		begint, _ = time.ParseInLocation("2006-01-02 15:04:05", begin, time.Local)
	}
	if end == "" {
		d, _ := time.ParseDuration("72h")
		endt := begint.Add(d)
		end = endt.Format("2006-01-02 15:04:05")
	}
	fmt.Println("***********", begin, end)
	return begin, end
}

//InitPicApi 初始化api
func InitPicApi(r *gin.RouterGroup) {
	picAPI := r.Group("/picApi")
	{
		picAPI.GET("", func(c *gin.Context) {
			ipcId := c.Query("ipcId")
			beginTime := c.Query("begin")
			endTime := c.Query("end")
			beginTime, endTime = makeCondition(beginTime, endTime)
			var result []pic.PICInfo
			var err error
			if ipcId == "" {
				err = dbconn.DBConnection.Where("snap_time >= ? and snap_time <= ?", beginTime, endTime).Find(&result).Error
			} else {
				err = dbconn.DBConnection.Where("snap_time >= ? and snap_time <= ? and ipc_id=?", beginTime, endTime, ipcId).Find(&result).Error
			}
			webapi.SendResult(result, err, c)
		})
		picAPI.POST("/", func(c *gin.Context) {
			file, err := c.FormFile("files")
			if err != nil {
				webapi.SendError(err.Error(), webapi.ParamMissed, c)
				logger.SLog.Error("save pic error", err)
				return
			}

			dir, name, info := pic.ParseFileName(file.Filename)
			fmt.Println("*********picapi:", file.Filename, name)
			pThing, errt := cache.GetThing(info.IpcId)
			if errt != nil {
				webapi.SendError(errt.Error(), webapi.DBError, c)
				logger.SLog.Error("thing not found---------------", info.IpcId)

				return
			}
			info.IpcName = pThing.Thing.SName
			info.StationID = pThing.StationID
			info.StationName = pThing.GetStationName()
			os.MkdirAll(dir, os.ModePerm)
			src, errf := file.Open()
			if errf != nil {
				webapi.SendError(errf.Error(), webapi.ExtendError, c)
				logger.SLog.Error("file open error---------------", errf, dir, name)

				return
			}
			defer src.Close()
			dst, errc := os.Create(dir + "/" + name)
			if errc != nil {
				webapi.SendError(errc.Error(), webapi.ExtendError, c)
				logger.SLog.Error("create file---------------", errc)
				return
			}
			defer dst.Close()
			_, errw := io.Copy(dst, src)
			if errw != nil {
				webapi.SendError(errw.Error(), webapi.ExtendError, c)
				logger.SLog.Error("copy file---------------", errw)
				return
			}
			dbconn.DBConnection.Save(&info)
			webapi.SendOK(c)
			//io.Copy(dst, file)
			//webapi.SendOK(c)
			//filename := filepath.Base(file.Filename)

		})
	}
}
